package com.ashin;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * Hello world!
 *
 */
public class App {

    private static Logger logger = LoggerFactory.getLogger(App.class);

    private static final String url = "http://localhost:8081/test-web/TestServlet";

    private static final String logUrl = "http://localhost:8081/test-web/TestServlet";

    public static HttpClientContext context = HttpClientContext.create();

    private static int connectTimeout = 1000 * 50;

    private static int socketTimeout = 1000 * 5;

    private static int connectionRequestTimeout = 1000 * 2;

    public static void main(String[] args) throws ParseException, Exception {
        final CloseableHttpClient httpClient = createPoolHttpClient();
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        final SzDdjsUtil instance = new SzDdjsUtil();
        final Map<String, Object> params = new HashMap<>();
        int count = 4000;
        final CountDownLatch countDownLatch = new CountDownLatch(count);
        final AtomicInteger fail = new AtomicInteger(0);
        for (int i = 0; i < count; i++) {
            newCachedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                         instance.postJsonM(url, params);
//                        request(httpClient, params);

                    } catch (Exception e) {
                        fail.incrementAndGet();
                        logger.error("dddd", e);

                    } finally {
                        countDownLatch.countDown();
                    }
                }

            });
        }

        countDownLatch.await();

        logger.info("fail count {}", fail.get());

        // TimeUnit.SECONDS.sleep(10);
        newCachedThreadPool.shutdown();

    }

    public static void request(CloseableHttpClient httpClient, Map<String, Object> params) throws Exception {
        CloseableHttpResponse response = null;
        try {
            JSONObject jsonParam = new JSONObject();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                jsonParam.put(entry.getKey(), entry.getValue());
            }
            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
            entity.setContentEncoding("utf-8");
            entity.setContentType("application/json");

            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(entity);

            response = httpClient.execute(httpPost, context);
            Header[] allHeaders = response.getAllHeaders();
            for (Header header : allHeaders) {
                logger.info("name:{},value:{}", header.getName(), header.getValue());
            }

            String res = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(res);

        } catch (Exception e) {
            throw e;

        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    public static CloseableHttpClient createPoolHttpClient() {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // 将最大连接数增加到200
        cm.setMaxTotal(1000);
        // 将每个路由基础的连接增加到20
        cm.setDefaultMaxPerRoute(1000);

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
        System.out.println(httpClient);
        return httpClient;
    }

    public static CloseableHttpClient createHttpClient() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        System.out.println(httpClient);
        return httpClient;
    }

}
